<template>
  <div class="bill-setting">
    <div class="button-container">
      <el-select
          v-model="billInfo.bookName"
          placeholder="请选择账本名称"
          @focus="focusBookNameEvent"
          @change="selectBookNameEvent"
          style="width: 150px;">
        <el-option
            v-for="(item, index) in billInfo.billBookList"
            :key="index" :label="item.name" :value="item.name"
        />
      </el-select>

      <el-button type="primary" @click="addNewCategoryClick">新增类别</el-button>
    </div>

    <el-table
        :data="billInfo.billCategoryList"
        border stripe
        :header-cell-style="tableHeaderStyle()"
        :cell-style="tableCellStyle()"
        :row-style="tableRowStyle()"
        class="card-item">
      <el-table-column type="index" align="center" width="50"/>
      <el-table-column prop="name" label="名称" align="center" width="80"/>
      <el-table-column label="类型" align="center" width="80">
        <template #default="scope">
          <el-tag v-if="scope.row.type === 'expensive'" effect="dark" color="#CA6C65">支出</el-tag>
          <el-tag v-else effect="dark" color="#6FBB69">收入</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="图标" align="center" width="80">
        <template #default="scope">
          <i :class="scope.row.icon" :style="{color: scope.row.color, fontSize: '24px'}"></i>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150">
        <template #default="scope">
          <el-button type="primary" size="small" @click="editCategoryClick(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="deleteCategoryClick(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="billInfo.billCategoryDialog.visible"
               :title="billInfo.billCategoryDialog.title"
               center width="80%" @open="openDialogEvent">
      <el-form ref="formRef" :model="billInfo.billCategoryDialog.data"
               :rules="rules" label-position="top" label-width="100px">
        <el-form-item label="账本名称" prop="bookName">
          <el-select
              v-model="billInfo.billCategoryDialog.data.bookName"
              placeholder="请选择账本名称"
              @focus="focusBookNameEvent">
            <el-option
                v-for="(item, index) in billInfo.billBookList"
                :key="index" :label="item.name" :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="类别名称" prop="name">
          <el-input v-model="billInfo.billCategoryDialog.data.name" autocomplete="off"
                    placeholder="请输入类型名称"
                    :maxlength="10" show-word-limit/>
        </el-form-item>
        <el-form-item label="类型名称" prop="type">
          <el-radio-group v-model="billInfo.billCategoryDialog.data.type">
            <el-radio value="expensive">支出</el-radio>
            <el-radio value="income">收入</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="类别图标" prop="icon">
          <el-input v-model="billInfo.billCategoryDialog.data.icon" autocomplete="off"
                    placeholder="请输入类型图标"
                    :maxlength="40" show-word-limit/>
        </el-form-item>
        <el-form-item label="图标颜色" prop="color">
          <el-color-picker v-model="billInfo.billCategoryDialog.data.color" />
        </el-form-item>
        <el-form-item label="图标预览">
          <i :class="billInfo.billCategoryDialog.data.icon"
             :style="{color: billInfo.billCategoryDialog.data.color, fontSize: '24px'}"></i>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="confirmClick">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref } from 'vue'
import { useBillStore } from '@/store/bill.ts'
import { IBillBook, IBillCategory } from '@/types/bill.ts'
import { ElMessage, FormRules } from 'element-plus'
import { billCategoryRules } from '@/utils/element/elRules.ts'
import { addBillCategoryApi, updateBillCategoryApi } from '@/apis/bill.ts'
import { deepCopyObject } from 'vue3-common/utils/dataUtil'
import { tableHeaderStyle, tableRowStyle, tableCellStyle } from 'vue3-common/utils/elUtil'
import type { IDialog, IHandleApi } from 'vue3-common/types'

const formRef = ref()
const rules = reactive<FormRules>(billCategoryRules)
const billStore = useBillStore()

const billInfo = reactive({
  bookName: '日常账本',
  setBillCategoryType: 'ADD' as IHandleApi,
  billCategoryDialog: {
    title: '',
    visible: false,
    data: {}
  } as IDialog<IBillCategory>,
  billBookList: [] as IBillBook[],
  billCategoryList: [] as IBillCategory[]
})

onMounted(async () => {
  await billStore.queryBillCategory()
  queryBookCategoryByBookName(billInfo.bookName)
})

const selectBookNameEvent = (value: string) => {
  queryBookCategoryByBookName(value)
}

const queryBookCategoryByBookName = (bookName: string) => {
  billInfo.billCategoryList = billStore.billCategoryList.filter((item) => {
    return item.bookName === bookName
  })
}

/**
 * 点击新增类别按钮
 */
const addNewCategoryClick = () => {
  billInfo.setBillCategoryType = 'ADD'
  billInfo.billCategoryDialog = {
    title: '新增账单类别',
    visible: true,
    data: {
      bookName: '',
      name: '',
      type: '',
      icon: '',
      color: ''
    }
  }
}

/**
 * 点击编辑类别按钮
 * @param category 类别
 */
const editCategoryClick = async (category: IBillCategory) => {
  billInfo.setBillCategoryType = 'UPDATE'
  billInfo.billCategoryDialog = {
    title: '编辑账单类别',
    visible: true,
    data: deepCopyObject(category)
  }
}

/**
 * 点击删除类别按钮
 * @param category 类别
 */
const deleteCategoryClick = (category: IBillCategory) => {
  billInfo.setBillCategoryType = 'DELETE'
  ElMessage.error('暂不支持该功能')
}

const openDialogEvent = () => {
  nextTick(() => {
    formRef.value.clearValidate()
  })
}

const focusBookNameEvent = async () => {
  await billStore.queryBillBook()
  billInfo.billBookList = billStore.billBookList
}

const setBillCategoryApi = async (id?: number) => {
  switch (billInfo.setBillCategoryType) {
    case 'ADD':
      await addBillCategoryApi(billInfo.billCategoryDialog.data)
      ElMessage.success('新增账单类别成功')
      break
    case 'UPDATE':
      await updateBillCategoryApi(id as number, billInfo.billCategoryDialog.data)
      ElMessage.success('更新账单类别成功')
      break
    case 'DELETE':
      ElMessage.success('删除账单类别成功')
      break
    default:
      break
  }
  await billStore.queryBillCategory()
  billInfo.billCategoryDialog.visible = false
}

const cancelClick = () => {
  billInfo.billCategoryDialog.visible = false
}

const confirmClick = async () => {
  await formRef.value.validate(async (valid) => {
    if (valid) {
      await setBillCategoryApi(billInfo.billCategoryDialog.data.id)
      queryBookCategoryByBookName(billInfo.bookName)
    }
  })
}
</script>
